<template>
  <div></div>
</template>
<script>
export default {
  mounted() {
    function initWebsocket() {
      // clearInterval(timer.value);
      websocket.value = new WebSocket("ws://localhost:8080");
      const heartCheck = initHeartCheck(websocket.value);
      websocket.value.onopen = function () {
        // 获取当前链接的状态
        // 1 是建立了链接
        console.log(websocket.value, "ws");
        console.log(websocket.value.readyState, "state");
        // 启动心跳检测
        heartCheck.start();
      };
      websocket.value.onmessage = function (data) {
        // 启动心跳检测
        heartCheck.start();
        // 服务器返回过来的聊天信息
        console.log(data, "data");
      };
    }
    function initHeartCheck(ws) {
      return {
        timeout: 2 * 1000, // 每2s向服务端发送一次消息
        serverTimeout: 2 * 1000, // 2s收不到服务端消息算超时
        timer: null,
        serverTimer: null,
        reset() {
          // 心跳检测重置
          clearTimeout(this.timer);
          clearTimeout(this.serverTimer);
          this.timer = null;
          this.serverTimer = null;
          return this;
        },
        start() {
          // 心跳检测启动
          this.reset();
          this.timer = setTimeout(() => {
            ws.send("ping"); // 定时向服务端发送消息
            if (!this.serverTimer) {
              this.serverTimer = setTimeout(() => {
                // 关闭连接触发重连
                console.log(
                  new Date().toLocaleString(),
                  "not received pong, close the websocket"
                );
                initWebsocket(); // 重置ws链接
              }, this.serverTimeout);
            }
          }, this.timeout);
        },
      };
    }

    function send() {
      websocket.value.send(text.value);
    }

    function close() {
      websocket.value.close();
    }
  },
  methods: {},
};
</script>
